package com.googlecode.maratische.google.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import com.googlecode.maratische.google.MainFrame;
import com.googlecode.maratische.google.model.Label;

public class LabelForm extends JDialog {

	JTextArea textArea = new JTextArea();
	Label label = null;
	JComboBox comboBoxLabelType = null;
	
	public LabelForm(MainFrame mainFrame) {
		super(mainFrame, true);
		setSize(400, 300);
		setLayout(new BorderLayout());
		//радио кнопки
		comboBoxLabelType = new JComboBox();
		comboBoxLabelType.addItem("Почитать");
		comboBoxLabelType.addItem("Прокомментировать");
		comboBoxLabelType.addItem("Распечатать");
		JPanel panel1 = new JPanel();
		panel1.add(comboBoxLabelType);
		add(panel1, BorderLayout.NORTH);
		//комментарий
		add(textArea, BorderLayout.CENTER);
		//кнопки
		JPanel panel3 = new JPanel();
		add(panel3, BorderLayout.SOUTH);
		panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
		JButton buttonSave = new JButton("Сохранить");
		panel3.add(buttonSave);
		buttonSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doSaveLabel();
			}
		});
		JButton buttonCancel = new JButton("Отмена");
		panel3.add(buttonCancel);
		buttonCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});

		//key adapter
		KeyAdapter keyAdapter = new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == 10 && e.getModifiersEx()==128) {
					doSaveLabel();
				}
				if (e.getKeyCode() == 27) {
					close();
				}
			}
		};
		textArea.addKeyListener(keyAdapter);
		comboBoxLabelType.addKeyListener(keyAdapter);
		comboBoxLabelType.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == 10) {
					doSaveLabel();
				}
			}
		});
		textArea.setToolTipText("Ctrl-enter - сохранить");
		//init
	}
	
	private void doSaveLabel() {
		label = new Label();
		switch (comboBoxLabelType.getSelectedIndex()) {
		case 0:label.setType(Label.LABEL_TYPE_READ);break;
		case 1:label.setType(Label.LABEL_TYPE_COMMENT);break;
		case 2:label.setType(Label.LABEL_TYPE_PRINT);break;
		}
		label.setComment(textArea.getText());
		close();
	}

	public Label getLabel() {
		return label;
	}
	private void close() {
		this.dispose();
	}
	
	private static final long serialVersionUID = 5981928455489877939L;
}
